const app = getApp()
const api = wx.getStorageSync('api')
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    show: {
      type: Boolean,
      value: false
    },
    // 商品
    good: {
      type: Object,
      value: {}
    },
    // 规格
    specification: {
      type: Array,
      value: []
    },
    notBottom: {
      type: Boolean,
      value: true
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    currentIndex: 0, // 当前选中规格
    buyNum: 1 // 购买数量
  },


  /**
   * 组件的方法列表
   */
  methods: {
    // 显示组件
    show(good, notBottom) {
      if (notBottom == false) {
        this.setData({
          notBottom: false
        })
      }
      const url = api.specification + `?goodId=${good.id}`
      app.$http.get(url).then(res => {
        this.setData({
          specification: res.data.specification,
          good: good,
          show: true,
          buyNum: 1
        })
      })
    },

    // 关闭组件
    close() {
      this.setData({
        show: false
      });
    },

    // 商品规格点击
    selectTag(e) {
      this.setData({
        currentIndex: e.currentTarget.dataset.index
      })
      console.log('规格点击' + this.data.currentIndex)
    },

    // 购买数量改变
    onChange(e) {
      this.setData({
        buyNum: e.detail
      })
    },

    // 提交加入购物车
    addCart() {
      let good = this.data.good
      let specification = this.data.specification
      let data = {
        gid: good.id,
        gsid: specification.length == 0 ? 0 : specification[this.data.currentIndex].id,
        number: this.data.buyNum,
        uid: wx.getStorageSync('user').id
      }
      const url = api.car_add
      console.log(data, url);
      app.$http.post(url, data).then(res => {
        console.log(res)
        this.setData({
          show: false
        })
        if (res.code == 200) {
          wx.showToast({
            title: '已加入',
            icon: 'success'
          })
        } else {
          wx.showToast({
            title: res.message,
            icon: 'none'
          })
        }
      })
    },

    buyGood() {
      wx.showToast({
        title: '请前往购物车结算',
        icon: 'none',
        duration: 2000
      })
    }
  }
})